PAGE-9

CHAPTER-3(Packages and Interfaces)    

                               BOTTOM

Packages:-

Package:- A package in java is an encapsulation mechanism which is used to group related classes, interface and sub packages.Packages is simply a folder.

      With the help of packages we can represent an organization of java classes and interfaces. At  most one package declaration can appear in a source file and it  must be the first statement in the program.

 

Declaring a package:-

Using the package key word followed by the package name uses a package.

Example:-

package  packagename,

Above the package is a keyword and package name is any qualified name.

Using package: -

Once the packages are defined and classes are placed in those packages ,we can use these classes by other classes which are in same package or in another package. In our program we access the classes and interfaces in other packages using the import statement.

Example:-

Import < package name>

If we want to access all the members of the package we use the following statement.

import < package name>.

Example:- import java .util.*

All the classes and interfaces in the java.util package will be accessed in our program.

If we want to use a particular class in the packages, then we will use the following statement.

     import java.io.File;

Above the io is a package and File is a class defined in the package.

Packages can also be nested, as is mentioned in the above example.

java is the super package and io is the sub package which is defined in package “java” .

Creating the packages:

A package is nothing but a simple folder which contains the classes and interfaces, which are related, and of similar nature like square triangle, rectangle, all these classes are related, so that we can put them in a same package.

Compiling running programs using the packages.

Following is a file using a package keyword:-

package MyPackage;
/* Now, the Balance class, its constructor, and its
show() method are public. This means that they can
be used by non-subclass code outside their package.
*/

public class Balance {
String name;
double bal;
public Balance(String n, double b) {
name = n;
bal = b;
}
public String show() {
if(bal<0)
System.out.print("--> ");
System.out.println(name + ": $" + bal);
return name + " " + bal;

}
public static void main(String args[]){

Balance b = new Balance("raj",1000.00);

System.out.println("Values are shown "+b.show());
}}

Save this file as Balance.java in a folder MyPackage in any drive eg .D:

*Steps:-
             1. Create a folder having the same name declared in our program using the package keyword, eg. package myPackage;

2.Create a java fiv with the code above and put it your java file a in the folder created above now complile it using javac Balanace.java,a Balance.class file will be created .put that class file in the same folder above.

3.Once the file is compiled. Go to that one directory above directory which is a D: using the cd.. command on dos promt, and run the program as follows.

java packagename.classfile name.//This is the syntax

java MyPackage.Balance //This is the actual command you have to type.

 


 
He we have run our program using the package we have created earlier followed by the   "." Operator and complied file name.

Importing Package:-

We import packages with the help of import keyword.A class can call another class defined in another package. The class Balance.javamentioned above is is contained in package MyPackage. If a class in other package wants to access the servises of this class then that class will have to import the package MyPackage in its class.

Below is a class Testclass.java which is importing package MyPackage and using class Balance.java defined in this package.

 

import MyPackage.*;
class TestBalance {
public static void main(String args[]) {
/* Because Balance is public, you may use Balance
class and call its constructor. */

Balance test = new Balance("J. J. Jaspers", 99.88);
test.show(); // you may also call show()
}
}


Interface:-

Interface provides us to create a special data type. It contains the methods prototypes(ie.methods without body) and the named constants or constants. Method prototypes in an interface are important in the sense that they provide us a contract which tells us what should be done by these method but doesn’t tell that how it should be done.
 
         Interfaces are created for being implemented by the classes, so that many classes can implement the interface and provide its own implementation of the methods, so interface provide us single interface and multiple methods type of polymorphism.

Features of Interfaces:-

1.Interfaces contain method prototypes and constants.

2.A class can contains multiple interface, so interfaces provide multiple interfaces inheritance where as class provides a single implementation inheritance.

3. We use interfaces in our class using the implements classes.

4. An interface can extend multiple interfaces.

5. Accessibility modifies for interfaces are public or default. Members in the interface are declared as public, so that they can be accessed from anywhere in our application .

    Syntax:-

< accessibility modifies> interface < interface name,>

extends interface clause {

// interface body

< constant declarations>
<methods prototypes>

Above the structure of interface is defined.

1.Accessibility modifier are either public or defaults.

2. Interface is a keyword to indicate that we are defining interface.

3. Interface name is any logical name we want to give our interface.

4. Extends is also a keyword that is used to inherit the members of another interface by the calling interface .

5. Interface body has two types of members 1.Constants 2.Method prototypes.

6.Constants are variables which have a fixed values, and are implicitly public, static and final.

They are public, so that other classes can access them, another classes outside the package in which interface is defined. They are static, so that they are accessed through interface name or reference variable of interface , because we can not create an object of an interface because interface are incomplete like the abstract classes, they do not have implementation of the methods.7.Method prototypes only declare the method name and return type and end with a semi colon. Interfaces with empty bodies are called marker interfaces. Example of marker interfaces are java.lang. cloneable, java.io.Serializable, java.util.Eventlisterner , java.util.Set interface.

Example:-

Here is an interface definition. It declares a simple interface Callback which
contains one method called callback( ) that takes a single integer parameter

interface Callback {
void callback(int param);
}

Class and Interface:-

1. A class provides the implementation whereas interface provides the contract of methods by method prototype.

2.We can create object of class but we cannot create an object of an interface instead we create a reference of an interface.

3.Members of a class can be accessed through objects or refernce of a class but the members of an interface will be accessed only by reference of the interface.

4.A class provides single interitance whereas interface provides multiples inheritance.

5.A class can be abstract only if it does not provide an implementation of a declared method in its body ,on the other hand interface is implicitely abstract because it does not have an implementation of its methods .

6.Members in the interface are public whereas members in the class can be public,private,protected or default.

 

The differences between abstract class an interface as fallows:

1.  Abstract class has the constructor, but interface doesn’t.

2.  Abstract classes can have implementations for some of its members (Methods), but the interface can’t have implementation for any of its members.

3.  Abstract classes should have subclasses else that will be useless..

4. Interfaces must have implementations by other classes else that will be useless

5. Only an interface can extend another interface, but any class can extend an abstract class..

6.  All variable in interfaces are final by default

7. Interfaces provide a form of multiple inheritance. A class can extend only one other class.

8. Interfaces are limited to public methods and constants with no implementation. Abstract classes can have a partial implementation, protected parts, static methods, etc.

9.  A Class may implement several interfaces. But in case of abstract class, a class may extend only one abstract class.

10. Interfaces are slow as it requires extra indirection to find corresponding method in the actual class. Abstract classes are fast.

11. Accessibility modifier(Public/Private/internal) is allowed for abstract class. Interface doesn’t allow accessibility modifier

12.  An abstract class may contain complete or incomplete methods. Interfaces can contain only the signature of a method but no body. Thus an abstract class can implement methods but an interface can not implement methods.

13.  An abstract class can contain fields, constructors, or destructors and implement properties. An interface can not contain fields, constructors, or destructors and it has only the property’s signature but no implementation.

14. Various access modifiers such as abstract, protected, internal, public, virtual, etc. are useful in abstract Classes but not in interfaces.

15.  Abstract scope is upto derived class.

16.  Interface scope is upto any level of its inheritance chain.

 

 

Implementing Interfaces


Once an interface has been defined, one or more classes can implement that interface. To implement an interface, include the implements clause in a class definition, and then create the methods defined by the interface. The general form of a class that includes the implements clause looks like this:

access class classname [extends superclass]
[implements interface [interface...]] {
// class-body
}


Here, access is either public or not used. If a class implements more than one interface, the interfaces are separated with a comma. If a class implements two interfaces that declare the same method, then the same method will be used by clients of either interface. The methods that implement an interface must be declared public. Also, the type signature of the implementing method must match exactly the type signature specified in the interface definition.

Here is a small example class that implements the Callback interface shown earlier.


class Client implements Callback {
// Implement Callback's interface
public void callback(int p) {
System.out.println("callback called with " + p);
}
}

Notice that callback( ) is declared using the public access specifier. When you implement an interface method, it must be declared as public. It is both permissible and common for classes that implement interfaces to define additional members of their own. For example, the following version of Client implements callback( ) and adds the method nonIfaceMeth( ):


class Client implements Callback {
// Implement Callback's interface
public void callback(int p) {
System.out.println("callback called with " + p);
}
void nonIfaceMeth() {
System.out.println("Classes that implement interfaces " +
"may also define other members, too.");
}
}

Accessing Implementations Through Interface References


You can declare variables as object references that use an interface rather than a class type. Any instance of any class that implements the declared interface can be referred to by such a variable. When you call a method through one of these references, the correct version will be called based on the actual instance of the interface being referred to. This is one of the key features of interfaces. The method to be executed is looked up dynamically at run time.

The following example calls the callback( ) method via an interface reference variable

:
class TestIface {
public static void main(String args[]) {
Callback c = new Client();
c.callback(42);
}
}


The output of this program is shown here:

callback called with 42

Notice that variable c is declared to be of the interface type Callback, yet it was
assigned an instance of Client. Although c can be used to access the callback( )
method, it cannot access any other members of the Client class. An interface reference variable only has knowledge of the methods declared by its interface declaration. Thus, c could not be used to access nonIfaceMeth( ) since it is defined by Client but not Callback.

Calling methods through interface referance is used in serven side implementations where we call methods remotely,we use interface referance because we cannot access methods remotely through class objects.

 

Partial Implementations

If a class includes an interface but does not fully implement the methods defined by
that interface, then that class must be declared as abstract

.Example

abstract class Incomplete implements Callback {
int a, b;
void show() {
System.out.println(a + " " + b);
}
// ...
}


Here, the class Incomplete does not implement callback( ) and must be declared as abstract. Any class that inherits Incomplete must implement callback( ) or be declared abstract itself.


Note :
After Successful completion of Training Candidate will be provided with Project Report and Training Certificate.

Home  |   FeedBack  |   Terms of Use  |   Contact Us  |   Report Error
                                                                            Copyright © 2009 R.M Infotech (P) Ltd.                                             Designed by: Raman